﻿using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyQQRobot
{
    public partial class Form1 : UIForm
    {
        public Form1()
        {
            InitializeComponent();
        }
        static Socket serverSocket;

        private void uiButton1_Click(object sender, EventArgs e)
        {
            if(radioButton1.Checked==false&&radioButton2.Checked==false)
            {
                UIMessageTip.ShowWarning("请选中发送好友还是群聊");
                return;
            }
            if (uiTextBox1.Text.Equals(""))
            {
                UIMessageTip.ShowWarning("请输入账号");
                return;
            }
            sendMsg(new Message("private", uiTextBox1.Text,"你好呀"));
        }

        public void sendMsg(Message message)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 5700));     //配置服务器IP：端口    
                Console.WriteLine("连接服务器成功！");
            }
            catch
            {
                Console.WriteLine("连接服务器失败，请按回车键退出！");
                return;
            }
            String payload;
            if (message.Msg_type.Equals("group"))
                payload = "GET /send_group_msg?group_id="+message.Number+ "&message=" + message.Msg + " HTTP/1.1\r\nHost:" + "127.0.0.1" + ":5700\r\nConnection: close\r\n\r\n";
            else
                payload = "GET /send_private_msg?user_id=" + message.Number + "&message=" + message.Msg + " HTTP/1.1\r\nHost:" + "127.0.0.1" + ":5700\r\nConnection: close\r\n\r\n";
            
            clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(payload));

            clientSocket.Shutdown(SocketShutdown.Both);     //关闭Socket
            clientSocket.Close();
            Console.WriteLine("发送完成");
        }

        public void listen()
        {
            int myPort = 41260;
            IPAddress ip = IPAddress.Parse("127.0.0.1");    //构造IP
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     //指定套接字类型：TCP模式
            //AddressFamily:网络类型  SocketType：套接字类型 ProtocolType:使用的网络协议
            serverSocket.Bind(new IPEndPoint(ip, myPort));  //绑定IP地址：端口
            serverSocket.Listen(100);                        //设定最多10个排队链接请求
            Console.WriteLine("启动监听{0}成功!", serverSocket.LocalEndPoint.ToString());
            //通过Client_Socket发送数据
            Thread myThread = new Thread(ListenClientConnect);  //创建一个新的线程，并用于监听客户端链接
            myThread.Start();
            

        }

        //监听客户端链接
        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();    //同意链接
                clientSocket.Send(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\n\n"));     //字符串转换为字节数组，并发送.按照htpp的响应码才行，不然会一直重发
                Thread receiverThread = new Thread(ReceiveMessage);
                receiverThread.Start(clientSocket);
            }
        }



        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            byte[] result = new byte[2048];
            try
            {
                //通过clientSocket接收数据
                int receiveNumber = myClientSocket.Receive(result);     //接收缓冲数组，并读取数组内容
                String httpBody = Encoding.UTF8.GetString(result, 0, receiveNumber);
                Console.WriteLine("接收客户端{0}消息{1}.", myClientSocket.RemoteEndPoint.ToString(), httpBody);
                //Regex rg = new Regex("(?<=(" + "{"+ "))[.\\s\\S]*?(?=(" + "}" + "))", RegexOptions.Multiline | RegexOptions.Singleline);
                int index = httpBody.IndexOf('{');
                Console.WriteLine(index);
                String m = httpBody.Substring(index, httpBody.Length - 1-index);
                Console.WriteLine("匹配后的字符串:"+m);
                
                MessageInfo messageInfo= JsonConvert.DeserializeObject<MessageInfo>(m);
                if ("2399484724".Equals(messageInfo.User_id.ToString()))
                {
                    
                    Console.WriteLine("messageinfo.message=" + messageInfo.Message);
                    ChatRobot.answer(messageInfo.User_id.ToString(), messageInfo.Message);
                }
               
                //return rg.Match(str).Value;
                //Console.WriteLine("匹配后的字符串:" + rg.Match(Encoding.UTF8.GetString(result, 0, receiveNumber)).Value);
            }
            catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    return;
                }
            myClientSocket.Shutdown(SocketShutdown.Both);
            myClientSocket.Close();
        }


       public class Message
        {
            private String msg_type;
            private String number;
            private String msg;

            public Message(string msg_type, string number, string msg)
            {
                this.msg_type = msg_type;
                this.number = number;
                this.msg = msg;
            }

            public string Number { get => number; set => number = value; }
            public string Msg_type { get => msg_type; set => msg_type = value; }
            public string Msg { get => msg; set => msg = value; }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            listen();
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            String srcText = "找一个能长期代课的 量大管够 具体详聊qq：1164750389";
            String[] targetText = new string[] {"签到","代课" };
            WordMatchResponse wordMatchResponse= MyNPL.wordMatch(srcText,targetText);
            UIMessageBox.Show(JsonConvert.SerializeObject(wordMatchResponse));
        }

        private void uiTextBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
